package org.x.yuenovel.util;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.x.yuenovel.controller.dto.CaptchaDTO;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author xuezhendong
 * @date 2022/4/22 11:21 下午
 */
@Slf4j
@Component
public class CaptchaUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public CaptchaDTO getCaptchaCode(){
        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 39, 5);
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_ONLY_CHAR);
        String key = UUID.randomUUID().toString();
        String code = specCaptcha.text().toLowerCase();
        log.info("发送验证码：{}", code);
        stringRedisTemplate.opsForValue().set(key, code, 1, TimeUnit.MINUTES);
        return CaptchaDTO.builder().key(key).image(specCaptcha.toBase64()).build();
    }
}
